﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;

namespace Sinacor.Infra.Tools.ServiceRegistration.Data
{
    public class Method : ResourceAccess
    {
        #region Methods

        public List<Entity.Method> SelectMethod(Entity.Method entity, bool addCharacterLike)
        {
            List<Entity.Method> response = null;

            StringBuilder sql = new StringBuilder();

            sql.AppendLine("SELECT ");
            sql.AppendLine("    COD_MET_SERV, ");
            sql.AppendLine("    COD_TIPO_PARM_RETO_MET, ");
            sql.AppendLine("    COD_SERV, ");
            sql.AppendLine("    NOME_MET_SERV, ");
            sql.AppendLine("    DESC_MET_SERV, ");
            sql.AppendLine("    NOME_TABL_UTI_MET, ");
            sql.AppendLine("    IND_COLE, ");
            sql.AppendLine("    IC_STATUS, ");
            sql.AppendLine("    DATA_ALTE, ");
            sql.AppendLine("    (SELECT MAX(DATA_ALTE) FROM TFWDMOD) DATA_ALTE_MAX ");
            sql.AppendLine("FROM ");
            sql.AppendLine("    TFWDMET_SERV ");
            sql.AppendLine("WHERE ");
            sql.AppendLine("    (COD_MET_SERV = :COD_MET_SERV OR :COD_MET_SERV IS NULL) AND ");
            sql.AppendLine("    (COD_TIPO_PARM_RETO_MET = :COD_TIPO_PARM_RETO_MET OR :COD_TIPO_PARM_RETO_MET IS NULL) AND ");
            sql.AppendLine("    (COD_SERV = :COD_SERV OR :COD_SERV IS NULL) AND ");
            sql.AppendLine("    (UPPER(NOME_MET_SERV) LIKE UPPER(:NOME_MET_SERV) OR :NOME_MET_SERV IS NULL) AND ");
            sql.AppendLine("    (UPPER(DESC_MET_SERV) LIKE UPPER(:DESC_MET_SERV) OR :DESC_MET_SERV IS NULL) AND ");
            sql.AppendLine("    (UPPER(NOME_TABL_UTI_MET) LIKE UPPER(:NOME_TABL_UTI_MET) OR :NOME_TABL_UTI_MET IS NULL) AND ");
            sql.AppendLine("    (IND_COLE = :IND_COLE OR :IND_COLE IS NULL) AND ");
            sql.AppendLine("    (IC_STATUS = :IC_STATUS OR :IC_STATUS IS NULL) ");
            sql.AppendLine("ORDER BY NOME_MET_SERV");

            using (IDbCommand command = this.GetSqlStringCommand(sql.ToString()))
            {
                this.AddInParameter(command, "COD_MET_SERV", DbType.Int32, entity.MethodId);
                this.AddInParameter(command, "COD_TIPO_PARM_RETO_MET", DbType.Int32, entity.ReturnType != null ? entity.ReturnType.TypeId : null);
                this.AddInParameter(command, "COD_SERV", DbType.Int32, entity.Service != null ? entity.Service.ServiceId : null);
                this.AddInParameter(command, "NOME_MET_SERV", DbType.String, addCharacterLike == true ? AddCharacterLike(entity.MethodName) : entity.MethodName);
                this.AddInParameter(command, "DESC_MET_SERV", DbType.String, addCharacterLike == true ? AddCharacterLike(entity.Description) : entity.Description);
                this.AddInParameter(command, "NOME_TABL_UTI_MET", DbType.String, addCharacterLike == true ? AddCharacterLike(entity.RelatedTables) : entity.RelatedTables);
                this.AddInParameter(command, "IND_COLE", DbType.String, entity.IsReturnCollection.HasValue ? entity.IsReturnCollection.Value ? "S" : "N" : null);
                this.AddInParameter(command, "IC_STATUS", DbType.String, entity.StatusApproval.HasValue ? entity.StatusApproval == Entity.StatusApproval.Aprovado ? "0" : "1" : null);

                response = this.FindAll<Entity.Method>(command,
                    (
                        reader => new Entity.Method
                        {
                            MethodId = reader.GetValue<int>("COD_MET_SERV"),
                            MethodName = reader.GetValue<string>("NOME_MET_SERV"),
                            Description = reader.GetValue<string>("DESC_MET_SERV"),
                            RelatedTables = reader.GetValue<string>("NOME_TABL_UTI_MET"),
                            IsReturnCollection = reader.GetValue<string>("IND_COLE") == "S",
                            Parameters = GetParameters(reader.GetValue<int>("COD_MET_SERV")),
                            ReturnType = GetType(reader.GetValue<int>("COD_TIPO_PARM_RETO_MET")),
                            Service = entity.Service != null ? entity.Service : GetService(reader.GetValue<int>("COD_SERV")),
                            StatusApproval = reader.GetValue<string>("IC_STATUS") == "0" ? Entity.StatusApproval.Aprovado : Entity.StatusApproval.AguardandoAprovacao,
                            DateChange = reader.GetValue<DateTime>("DATA_ALTE"),
                            IsItemDivergent = !reader.GetValue<DateTime>("DATA_ALTE").Equals(reader.GetValue<DateTime>("DATA_ALTE_MAX")),
                        }
                    )
                );
            }

            return response;
        }

        public Entity.Method InsertMethod(Entity.Method entity)
        {
            StringBuilder sql = new StringBuilder();

            sql.AppendLine("INSERT INTO TFWDMET_SERV ( ");
            sql.AppendLine("    COD_MET_SERV, ");
            sql.AppendLine("    COD_TIPO_PARM_RETO_MET, ");
            sql.AppendLine("    COD_SERV, ");
            sql.AppendLine("    NOME_MET_SERV, ");
            sql.AppendLine("    DESC_MET_SERV, ");
            sql.AppendLine("    NOME_TABL_UTI_MET, ");            
            sql.AppendLine("    IND_COLE, ");
            sql.AppendLine("    IC_STATUS, ");
            sql.AppendLine("    DATA_ALTE ");
            sql.AppendLine("    ) VALUES ( ");
            sql.AppendLine("    :COD_MET_SERV, ");
            sql.AppendLine("    :COD_TIPO_PARM_RETO_MET, ");
            sql.AppendLine("    :COD_SERV, ");
            sql.AppendLine("    :NOME_MET_SERV, ");
            sql.AppendLine("    :DESC_MET_SERV, ");
            sql.AppendLine("    :NOME_TABL_UTI_MET, ");            
            sql.AppendLine("    :IND_COLE, ");
            sql.AppendLine("    :IC_STATUS, ");

            if (entity.DataOrigin == Entity.DataOrigin.Loader)
                sql.AppendLine("    :DATA_ALTE) ");
            else
                sql.AppendLine("    (SELECT MAX(DATA_ALTE) FROM TFWDMOD)) ");

            using (IDbCommand command = this.GetSqlStringCommand(sql.ToString()))
            {
                this.AddInParameter(command, "COD_MET_SERV", DbType.Int32, entity.MethodId);
                this.AddInParameter(command, "COD_TIPO_PARM_RETO_MET", DbType.Int32, entity.ReturnType != null ? entity.ReturnType.TypeId : null);
                this.AddInParameter(command, "COD_SERV", DbType.Int32, entity.Service != null ? entity.Service.ServiceId : null);
                this.AddInParameter(command, "NOME_MET_SERV", DbType.String, entity.MethodName);
                this.AddInParameter(command, "DESC_MET_SERV", DbType.String, entity.Description);
                this.AddInParameter(command, "NOME_TABL_UTI_MET", DbType.String, entity.RelatedTables);
                this.AddInParameter(command, "IND_COLE", DbType.String, entity.IsReturnCollection.HasValue ? entity.IsReturnCollection.Value ? "S" : "N" : null);
                this.AddInParameter(command, "IC_STATUS", DbType.String, entity.StatusApproval == Entity.StatusApproval.Aprovado ? "0" : "1");

                if (entity.DataOrigin == Entity.DataOrigin.Loader)
                    this.AddInParameter(command, "DATA_ALTE", DbType.Date, entity.DateChange);

                this.ExecuteNonQuery(command);
            }

            return entity;
        }

        public void UpdateMethod(Entity.Method entity)
        {
            StringBuilder sql = new StringBuilder();

            sql.AppendLine("UPDATE TFWDMET_SERV SET ");
            sql.AppendLine("COD_TIPO_PARM_RETO_MET = :COD_TIPO_PARM_RETO_MET, ");
            sql.AppendLine("COD_SERV = :COD_SERV, ");
            sql.AppendLine("NOME_MET_SERV = :NOME_MET_SERV, ");
            sql.AppendLine("DESC_MET_SERV = :DESC_MET_SERV, ");
            sql.AppendLine("NOME_TABL_UTI_MET = :NOME_TABL_UTI_MET, ");            
            sql.AppendLine("IND_COLE = :IND_COLE, ");
            sql.AppendLine("IC_STATUS = :IC_STATUS ");

            if (entity.DataOrigin == Entity.DataOrigin.Loader)
                sql.AppendLine(", DATA_ALTE = :DATA_ALTE ");

            sql.AppendLine("WHERE COD_MET_SERV = :COD_MET_SERV ");

            using (IDbCommand command = this.GetSqlStringCommand(sql.ToString()))
            {
                this.AddInParameter(command, "COD_MET_SERV", DbType.Int32, entity.MethodId);
                this.AddInParameter(command, "COD_TIPO_PARM_RETO_MET", DbType.Int32, entity.ReturnType != null ? entity.ReturnType.TypeId : null);
                this.AddInParameter(command, "COD_SERV", DbType.Int32, entity.Service != null ? entity.Service.ServiceId : null);
                this.AddInParameter(command, "NOME_MET_SERV", DbType.String, entity.MethodName);
                this.AddInParameter(command, "DESC_MET_SERV", DbType.String, entity.Description);
                this.AddInParameter(command, "NOME_TABL_UTI_MET", DbType.String, entity.RelatedTables);
                this.AddInParameter(command, "IND_COLE", DbType.String, entity.IsReturnCollection.HasValue ? entity.IsReturnCollection.Value ? "S" : "N" : null);
                this.AddInParameter(command, "IC_STATUS", DbType.String, entity.StatusApproval == Entity.StatusApproval.Aprovado ? "0" : "1");

                if (entity.DataOrigin == Entity.DataOrigin.Loader)
                    this.AddInParameter(command, "DATA_ALTE", DbType.Date, entity.DateChange);

                this.ExecuteNonQuery(command);
            }
        }

        public void DeleteMethod(Entity.Method entity)
        {
            Parameter p = new Parameter();
            string sql = "DELETE FROM TFWDMET_SERV WHERE COD_MET_SERV = :COD_MET_SERV";

            p.DeleteParameterByMethodId(new Entity.Parameter { Method = new Entity.Method { MethodId = entity.MethodId } }); 

            using (IDbCommand command = this.GetSqlStringCommand(sql))
            {
                this.AddInParameter(command, "COD_MET_SERV", DbType.Int32, entity.MethodId);
                this.ExecuteNonQuery(command);
            }
        }

        public void DeleteMethodByServiceId(Entity.Method entity)
        {
            Parameter p = new Parameter();
            string sql = "DELETE FROM TFWDMET_SERV WHERE COD_SERV = :COD_SERV";

            foreach (Entity.Method item in this.SelectMethod(entity, false))
            {
                p.DeleteParameterByMethodId(new Entity.Parameter { Method = item });
            }

            using (IDbCommand command = this.GetSqlStringCommand(sql))
            {
                this.AddInParameter(command, "COD_SERV", DbType.Int32, entity.Service.ServiceId);
                this.ExecuteNonQuery(command);
            }
        }

        public int GetNextMethodId()
        {
            int retorno = 0;
            string sql = " SELECT NVL(MAX(COD_MET_SERV) + 1, 1) FROM TFWDMET_SERV ";

            using (IDbCommand command = this.GetSqlStringCommand(sql))
            {
                retorno = Convert.ToInt32(this.ExecuteScalar(command));
            }

            return retorno;
        }

        private Entity.Type GetType(int id_type)
        {
            Type t = new Type();
            List<Entity.Type> responseList = null;
            Entity.Type response = null;

            if (id_type != 0)
            {
                responseList = t.SelectType(new Entity.Type { TypeId = id_type }, false);

                if (responseList != null && responseList.Count > 0)
                    response = responseList[0];
            }

            return response;
        }

        private Entity.Service GetService(int id_service)
        {
            Service t = new Service();
            List<Entity.Service> responseList = null;
            Entity.Service response = null;

            if (id_service != 0)
            {
                responseList = t.SelectService(new Entity.Service { ServiceId = id_service }, false);

                if (responseList != null && responseList.Count > 0)
                    response = responseList[0];
            }

            return response;
        }

        private List<Entity.Parameter> GetParameters(int id_method)
        {
            Parameter t = new Parameter();
            List<Entity.Parameter> response = null;

            if (id_method != 0)
            {
                response = t.SelectParameter(new Entity.Parameter { Method = new Entity.Method { MethodId = id_method } }, false);
            }

            return response;
        }

        #endregion
    }
}
